<?php

namespace app\controllers\h5\execute;

use app\controllers\h5\base\H5Controller;
use app\models\user\UserFav as Model;

/**
 * Class FavController
 * @package app\controllers\h5\execute
 */
class FavController extends H5Controller
{
    /**
     * check fav
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionCheck()
    {
        $id = intval($this->post('id'));
        $user_id = $this->user->id;

        $model = Model::findOne(['user_id' => $user_id, 'product_id' => $id]);
        if ($model) {
            return $this->successEncode(['is' => true]);
        }

        return $this->successEncode(['is' => false]);
    }

    public function actionCreate()
    {
        $id = intval($this->post('id'));
        $user_id = $this->user->id;

        $model = Model::findOne(['user_id' => $user_id, 'product_id' => $id]);
        if ($model) {
            return $this->success();
        }

        $data = [
            'UserFav' => [
                'user_id' => $user_id,
                'product_id' => $id
            ]
        ];
        $model = new Model();
        if ($model->load($data) && $model->save()) {
            return $this->success();
        }

        return $this->fail('收藏失败');
    }

    public function actionDelete()
    {
        $id = intval($this->post('id'));
        $user_id = $this->user->id;

        $model = Model::findOne(['user_id' => $user_id, 'product_id' => $id]);
        if ($model && $model->delete()) {
            return $this->success();
        }

        return $this->fail('删除失败');
    }

    public function actionList()
    {
        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = Model::find()
            ->where(['user_id' => $this->user->id]);

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with(['product', 'product.mainImage'])
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }
}